const xss = require('xss');
const path = require('path');
const {exec} = require('../db/mysql');
const {SuccessModel, ErrorModel} = require('../model/resModel');

const showMusics = async (ctx, next) => {
    const uid = ctx.session.user.id;
    const sql = `select * from music where uid = ${uid}`;
    const musics = await exec(sql);
    ctx.render('index', {musics});
};

const showEdit = async (ctx, next) => {
    const id = ctx.query.id;
    const sql = `select * from music where id = ${id}`;
    const musics = await exec(sql);
    if (musics.length === 0) {
        ctx.throw('歌曲不存在');
        return;
    }
    const music = musics[0];
    ctx.render('edit', {music});
};

function uploadFile(ctx) {
    let {title, singer, time} = ctx.request.body;
    let {file, lrc} = ctx.request.files;
    let singObj = {title, singer, time};
    singObj.lrc = 'no upload lrc';
    // 歌词
    if (lrc) {
        // 文件路径
        singObj.lrc = '/public/files/' + path.parse(lrc.path).base;
    }
    if (!file) {
        ctx.throw('歌曲必须上传');
        return;
    }
    singObj.file = '/public/files/' + path.parse(file.path).base;
    // 用户ID
    singObj.uid = ctx.session.user.id;
    return singObj;
}

const addMusic = async (ctx, next) => {
    const singObj = uploadFile(ctx);
    const title = xss(singObj.title);
    const singer = xss(singObj.singer);
    const createTime = Date.now();
    const sql = `insert into music(title, singer, time, file, lrc, uid, create_time) values ('${title}','${singer}','${singObj.time}','${singObj.file}','${singObj.lrc}',${singObj.uid},'${createTime}')`;
    const insertData = await exec(sql);
    if (insertData.affectedRows === 1) {
        ctx.body = new SuccessModel(insertData, insertData.message, '001');
    }

};

const editMusic = async (ctx, next) => {
    const singObj = uploadFile(ctx);
    const title = xss(singObj.title);
    const singer = xss(singObj.singer);
    const id = ctx.request.body.id;
    const sql = `update music set title='${title}',singer='${singer}',time='${singObj.time}',file='${singObj.file}',lrc='${singObj.lrc}' where id=${id} and uid=${singObj.uid}`;
    const updateData = await exec(sql);
    if (updateData.affectedRows !== 1) {
        ctx.body = new ErrorModel(updateData, '更新失败', '002');
        return;
    }
    ctx.body = new SuccessModel(updateData, '更新成功', '001');
};

const delMusic = async (ctx, next) => {
    const {id, uid} = ctx.request.body;
    const sql = `delete from music where id=${id} and uid=${uid}`;
    const delData = await exec(sql);
    if (delData.affectedRows === 0) {
        ctx.body = new ErrorModel(delData, '删除失败', '002');
        return;
    }
    ctx.body = new SuccessModel(delData, '删除成功', '001');
};

module.exports = {showMusics, showEdit, addMusic, editMusic, delMusic};